package org.ym.system.application.commandservice;

import com.google.common.base.Preconditions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ym.system.domain.command.SysUserCommand;
import org.ym.system.domain.model.entity.SysUser;
import org.ym.system.domain.repository.SysUserRepositoryService;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author ym
 */
@Service
public class SysUserCommandService {
    @Resource
    SysUserRepositoryService sysUserRepositoryService;

    /**
     * 创建
     * @param sysUserCommand 命令
     * @return SysUserVO
     */
    @Transactional(rollbackFor = Exception.class)
    public SysUser create(SysUserCommand sysUserCommand){
        SysUser sysUser = SysUser.of(sysUserCommand);
        sysUser = sysUserRepositoryService.insertAndFlush(sysUser);
        return sysUser;
    }

    /**
     * 更新
     * @param sysUserCommand 命令
     * @return SysUserVO
     */
    @Transactional(rollbackFor = Exception.class)
    public SysUser update(SysUserCommand sysUserCommand){
        Preconditions.checkNotNull(sysUserCommand);
        SysUser sysUser = null;
        Optional<SysUser> optionalSysUser = sysUserRepositoryService.getById(sysUserCommand.getId());
        if(optionalSysUser.isPresent()) {
            sysUser = optionalSysUser.get();
            sysUser.mutate(sysUserCommand);
            sysUser = sysUserRepositoryService.updateAndFlush(sysUser);
        }
        return sysUser;
    }
    /**
     * 保存
     * @param sysUserCommand 命令
     * @return SysUserVO
     */
    @Transactional(rollbackFor = Exception.class)
    public SysUser save(SysUserCommand sysUserCommand){
        Preconditions.checkNotNull(sysUserCommand);
        if(sysUserCommand.getId() == null){
            return create(sysUserCommand);
        }else{
            return update(sysUserCommand);
        }
    }
}
